package com.lsl.endworkvol.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lsl.endworkvol.entity.SignUpNote;
import com.lsl.endworkvol.entity.Volunteer;
import com.lsl.endworkvol.dao.SignUpNoteMapper;
import com.lsl.endworkvol.dao.VolunteerMapper;
import com.lsl.endworkvol.service.VolunteerService;
import com.lsl.endworkvol.service.func.IUserBuilder;

@Service
public class VolunteerServiceImpl implements VolunteerService{

    @Autowired
    private VolunteerMapper volunteerMapper;

    @Autowired
    private SignUpNoteMapper signUpNoteMapper;

    @Override
    public boolean addUser(IUserBuilder builder) {
        return volunteerMapper.insertVolunteer((Volunteer)builder.build()) > 0;
    }

    @Override
    public boolean editUser(IUserBuilder builder) {
        Volunteer volunteer = (Volunteer)builder.build();
        if (volunteer.getName() == null) {    // 用户名为null：代表用户正在被重置信息
            Volunteer temp = getUser(volunteer.getId());
            volunteer.setName(temp.getName());
            volunteer.setPassword(temp.getPassword());
        }
        if (volunteer.getPassword().isEmpty()) {    // 密码为空：代表用户不修改密码
            volunteer.setPassword(getUser(volunteer.getId()).getPassword());
        }
        volunteer.setVolId(volunteerMapper.selectVolunteerById(volunteer.getId()).getVolId());  // 保证vol_id不变
        return volunteerMapper.updateVolunteer(volunteer) > 0;
    }

    @Override
    public Volunteer getUser(Integer id) {
        return volunteerMapper.selectVolunteerById(id);
    }

    @Override
    public List<Volunteer> getUsers(IUserBuilder builder) {
        return volunteerMapper.blurVolunteers((Volunteer)builder.build());
    }

    @Override
    public List<Volunteer> getUsers() {
        return volunteerMapper.selectAllVolunteers();
    }

    @Override
    public boolean deleteUser(Integer id) {
        List<SignUpNote> signUpNotes = signUpNoteMapper.selectByVolunteerId(id);
        for (SignUpNote signUpNote : signUpNotes) {
            signUpNoteMapper.delete(signUpNote.getId());
        }
        return volunteerMapper.deleteVolunteer(id) > 0;
    }

    @Override
    public boolean loginCheck(String id, String password) {
        Volunteer volunteer = getUser(Integer.parseInt(id));
        return volunteer != null && volunteer.getPassword().equals(password);
    }

}
